package com.atguigu.guli.api.gateway.filter;

import com.atguigu.guli.service.base.handler.JwtHelper;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class GlobalAuthFilter implements GlobalFilter , Ordered {
    //每次有请求访问网关项目时，该方法会自动执行
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //网关filter中的API是webflux的api和servlet的api不同，方法属性不同，但是封装的数据都是一样
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //统一鉴权：
        //1、判断当前路径是否满足要求： /api/**/auth/**
        String path = request.getURI().getPath();//获取当前请求的地址
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match = matcher.match("/api/**/auth/**", path);
        if(!match){
            //路径匹配失败，无需鉴权
            return chain.filter(exchange);
        }
        //2、如果满足，则开始鉴权
        //2.1 获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        //2.2 使用JwtHelper进行校验
        boolean checkToken = JwtHelper.checkToken(token);
        if(checkToken){
            //鉴权成功：已登录，放行请求
            return chain.filter(exchange);
        }
        //3、鉴权失败：给出失败的响应
        //响应R对象的json给前端
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("code" , ResultCodeEnum.LOGIN_AUTH.getCode());
        jsonObject.addProperty("success" , ResultCodeEnum.LOGIN_AUTH.getSuccess());
        jsonObject.addProperty("message" , ResultCodeEnum.LOGIN_AUTH.getMessage());
        String jsonR = jsonObject.toString();
        //准备响应头内容
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //准备响应体内容
        DataBuffer buffer = response.bufferFactory().wrap(jsonR.getBytes(StandardCharsets.UTF_8));
        Mono<DataBuffer> body = Mono.just(buffer);
        //4、如果鉴权成功或者无需鉴权 则放行请求

        return response.writeWith(body);
    }

    @Override
    public int getOrder() {
        return 0; //值越小filter执行的优先级越高
    }
}
